//
//  ZYTimer.swift
//  ZYUICommon
//
//  Created by Yi Zhou on 2025/1/11.
//

import Foundation

public class ZYTimer {
    
    private var timer: DispatchSourceTimer?
    private let interval: Double
    private let queue: DispatchQueue
    private var handler: (() -> Void)?
    
    public init(interval: Double, queue: DispatchQueue = .main, handler: @escaping () -> Void) {
        self.interval = interval
        self.queue = queue
        self.handler = handler
    }
    
    deinit {
        self.invalidate()
    }
    
    /// 开始
    public func start() {
        if timer == nil {
            // 创建调度源
            timer = DispatchSource.makeTimerSource(queue: queue)
            timer?.schedule(deadline: .now() + interval, repeating: interval)
            timer?.setEventHandler(handler: { [weak self] in
                self?.handler?()
            })
            timer?.resume()
        }
    }
    
    /// 暂停
    public func pause() {
        timer?.suspend()
    }
    
    /// 重启
    public func resume() {
        timer?.resume()
    }
    
    /// 清空
    public func invalidate() {
        timer?.cancel()
        // 清除引用以避免循环引用
        handler = nil
        timer = nil
    }
    
}
